// pages/dish/dish.js
import { checkLoginAndRedirect } from '../../utils/auth.js'

const app = getApp()

Page({
  data: {
    loading: true,
    dishId: null,
    dish: null,
    selectedFlavors: {},
    quantity: 1,
    cartCount: 0
  },

  onLoad(options) {
    const { id } = options
    this.setData({
      dishId: id
    })
    
    this.loadDishDetail()
  },

  onShow() {
    // 更新购物车数量
    this.updateCartCount()
  },

  // 加载菜品详情
  async loadDishDetail() {
    try {
      this.setData({ loading: true })
      
      // 模拟菜品数据，实际应该调用API
      const mockDish = {
        id: this.data.dishId,
        name: '宫保鸡丁',
        price: 28.00,
        image: '/images/dishes/dish1.jpg',
        description: '经典川菜，选用优质鸡胸肉，配以花生米、干辣椒等调料，麻辣鲜香，口感丰富。',
        categoryId: 1,
        categoryName: '热菜',
        status: 1,
        flavors: [
          { id: 1, name: '辣度', value: '微辣' },
          { id: 2, name: '辣度', value: '中辣' },
          { id: 3, name: '辣度', value: '特辣' }
        ]
      }
      
      this.setData({
        dish: mockDish,
        loading: false
      })
      
      // 设置导航栏标题
      wx.setNavigationBarTitle({
        title: mockDish.name
      })
    } catch (error) {
      console.error('加载菜品详情失败:', error)
      wx.showToast({
        title: '加载失败',
        icon: 'none'
      })
      this.setData({ loading: false })
    }
  },

  // 更新购物车数量
  updateCartCount() {
    app.updateCartCount()
    this.setData({
      cartCount: app.globalData.cartCount
    })
  },

  // 选择口味
  selectFlavor(e) {
    const { flavorId, value } = e.currentTarget.dataset
    const selectedFlavors = { ...this.data.selectedFlavors }
    selectedFlavors[flavorId] = value
    
    this.setData({
      selectedFlavors
    })
  },

  // 增加数量
  increaseQuantity() {
    this.setData({
      quantity: this.data.quantity + 1
    })
  },

  // 减少数量
  decreaseQuantity() {
    if (this.data.quantity > 1) {
      this.setData({
        quantity: this.data.quantity - 1
      })
    }
  },

  // 添加到购物车
  async addToCart() {
    if (!checkLoginAndRedirect()) return
    
    if (!this.data.dish || this.data.dish.status !== 1) {
      wx.showToast({
        title: '商品暂不可购买',
        icon: 'none'
      })
      return
    }
    
    try {
      wx.showLoading({ title: '添加中...' })
      
      // 构建口味字符串
      const flavorText = Object.values(this.data.selectedFlavors).join(',')
      
      const res = await wx.request({
        url: `${app.globalData.baseUrl}/user/shoppingCart/add`,
        method: 'POST',
        header: {
          'Content-Type': 'application/json',
          'Authorization': `Bearer ${app.globalData.token}`
        },
        data: {
          dishId: this.data.dishId,
          dishFlavor: flavorText
        }
      })
      
      if (res.data.code === 1) {
        wx.showToast({
          title: '添加成功',
          icon: 'success'
        })
        this.updateCartCount()
      } else {
        throw new Error(res.data.msg || '添加失败')
      }
    } catch (error) {
      console.error('添加到购物车失败:', error)
      wx.showToast({
        title: error.message || '添加失败',
        icon: 'none'
      })
    } finally {
      wx.hideLoading()
    }
  },

  // 立即购买
  async buyNow() {
    if (!checkLoginAndRedirect()) return
    
    if (!this.data.dish || this.data.dish.status !== 1) {
      wx.showToast({
        title: '商品暂不可购买',
        icon: 'none'
      })
      return
    }
    
    try {
      wx.showLoading({ title: '处理中...' })
      
      // 先添加到购物车
      const flavorText = Object.values(this.data.selectedFlavors).join(',')
      
      const addRes = await wx.request({
        url: `${app.globalData.baseUrl}/user/shoppingCart/add`,
        method: 'POST',
        header: {
          'Content-Type': 'application/json',
          'Authorization': `Bearer ${app.globalData.token}`
        },
        data: {
          dishId: this.data.dishId,
          dishFlavor: flavorText
        }
      })
      
      if (addRes.data.code === 1) {
        // 跳转到订单确认页面
        wx.navigateTo({
          url: '/pages/order/order'
        })
      } else {
        throw new Error(addRes.data.msg || '添加失败')
      }
    } catch (error) {
      console.error('立即购买失败:', error)
      wx.showToast({
        title: error.message || '操作失败',
        icon: 'none'
      })
    } finally {
      wx.hideLoading()
    }
  },

  // 跳转到购物车
  goToCart() {
    if (!checkLoginAndRedirect()) return
    
    wx.switchTab({
      url: '/pages/cart/cart'
    })
  },

  // 分享功能
  onShareAppMessage() {
    return {
      title: `${this.data.dish.name} - 美味外卖`,
      path: `/pages/dish/dish?id=${this.data.dishId}`,
      imageUrl: this.data.dish.image
    }
  }
})
